package rwheel

import (
	"context"
	"fmt"
	"time"
)

type Func func(funcKey string, ctx *context.Context)

func AddTimerFunc(key string, fx Func, ctx *context.Context, d time.Duration) error {
	_lockTimerMap.Lock()
	defer _lockTimerMap.Unlock()
	if _, ok := _timerMap[key]; ok {
		return fmt.Errorf("【%v】已存在", key)
	}
	if ctx == nil {
		background := context.Background()
		ctx = &background
	}
	_timerMap[key] = &_timerFunc{
		key:         key,
		ctx:         ctx,
		fx:          fx,
		nextRunTime: time.Now().Add(d).UnixMilli(),
	}
	return nil
}

func ResetTimerFunc(key string, d time.Duration) error {
	_lockTimerMap.Lock()
	defer _lockTimerMap.Unlock()
	if v, ok := _timerMap[key]; false == ok {
		return fmt.Errorf("【%v】不存在", key)
	} else {
		v.nextRunTime = time.Now().Add(d).UnixMilli()
		return nil
	}
}

func RemoveTimerFunc(key string) {
	_lockTimerMap.Lock()
	defer _lockTimerMap.Unlock()
	delete(_timerMap, key)
}

func SetParamsTimerFunc(key string, pKey any, pValue any) error {
	_lockTimerMap.Lock()
	defer _lockTimerMap.Unlock()
	if v, ok := _timerMap[key]; false == ok {
		return fmt.Errorf("【%v】不存在", key)
	} else {
		value := context.WithValue(*v.ctx, pKey, pValue)
		v.ctx = &value
		return nil
	}
}

// RangeTimerFunc 获取当前所有的定时器函数信息
func RangeTimerFunc() []FuncName {
	_lockTimerMap.Lock()
	defer _lockTimerMap.Unlock()
	var rt = make([]FuncName, 0, 10)
	for k, v := range _timerMap {
		rt = append(rt, FuncName{
			Key:     k,
			RunTime: v.nextRunTime,
		})
	}
	return rt
}
